package com.example.wanbaqian.fragment;

import android.content.ClipboardManager;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.TextUtils;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.example.wanbaqian.R;
import com.example.wanbaqian.activity.ApplyAgainActivity;
import com.example.wanbaqian.activity.ApplyOneActivity;
import com.example.wanbaqian.activity.BackMoneyOneActivity;
import com.example.wanbaqian.activity.WithdrawalsActivity;
import com.example.wanbaqian.bean.ApplyOneBean;
import com.example.wanbaqian.bean.HomeWalletBean;
import com.example.wanbaqian.bean.WalletFragmentMoeyBean;
import com.example.wanbaqian.bean.WithdrawalsBean;
import com.google.gson.Gson;
import com.liaoinstan.springview.widget.SpringView;
import com.example.wanbaqian.activity.HomeActivity;
import com.example.wanbaqian.adapter.AllRepayListAdpter;
import com.example.wanbaqian.base.BaseFragment;
import com.example.wanbaqian.config.CommonValue;
import com.example.wanbaqian.base.HttpCallback;
import com.example.wanbaqian.config.HttpURL;
import com.example.wanbaqian.base.RefreshCallback;
import com.example.wanbaqian.bean.AddMoneyBean;
import com.example.wanbaqian.bean.AllRepaylistBean;
import com.example.wanbaqian.bean.Info;
import com.example.wanbaqian.event.ValueEvent;
import com.example.wanbaqian.utils.GetJsonUtils;
import com.example.wanbaqian.utils.HttpUtils;
import com.example.wanbaqian.utils.JsonUtils;
import com.example.wanbaqian.utils.SPUtils;
import com.zhy.adapter.recyclerview.MultiItemTypeAdapter;
import com.zhy.adapter.recyclerview.wrapper.EmptyWrapper;
import com.zhy.autolayout.AutoLinearLayout;

import org.greenrobot.eventbus.EventBus;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import butterknife.OnClick;

/**
 * 待还款列表
 */
public class AddMoneyFragment extends BaseFragment implements HttpCallback, RefreshCallback, MultiItemTypeAdapter.OnItemClickListener {
    private static final String ARG_PARAM1 = "param1";
    private AddMoneyBean bean;
    @BindView(R.id.refresh_repay)
    SpringView mRefresh;

    @BindView(R.id.ll_norepaylist)
    RelativeLayout mNorepaylist;

    @BindView(R.id.llEmptyList)
    AutoLinearLayout llEmptyList;

    @BindView(R.id.txt_applylend)
    Button mApplylend;

    @BindView(R.id.rec_repaylist)
    RecyclerView mReclist;

    @BindView(R.id.llFootView)
    LinearLayout llFootView;

    @BindView(R.id.tvCoppy)
    TextView tvCoppy;

    private List<AllRepaylistBean> mList = null;
    private AllRepayListAdpter mAdpter;
    private EmptyWrapper emptyWrapper;
    private View mEmpty;
    private static final String TAG = "AddMoneyFragment";
    private HomeWalletBean bean1;

    public static AddMoneyFragment newInstance(String param1) {
        AddMoneyFragment fragment = new AddMoneyFragment();
        Bundle args = new Bundle();
        args.putString(ARG_PARAM1, param1);
        fragment.setArguments(args);
        return fragment;
    }


    @Override
    public void onHiddenChanged(boolean hidden) {
        super.onHiddenChanged(hidden);
        if(hidden){
        }else{
            setRequest();
            getUserHomeInfo();
        }
    }

    /**
     * 初始化按钮文案，和首页同步，需求提出者：测试王龙，确认者：苗佳 执行人：刘欢
     */
    private void getUserHomeInfo() {

        HttpUtils.getInstance().post(GetJsonUtils.getInstance().getRequest(HttpURL.MY_CREDIT, mContext,
                new String[]{"accessid"}, new String[]{SPUtils.getAccessid(mContext)}),
                mContext, "", CommonValue.REQUEST_CODE2, this);

    }

    @Override
    protected int getContentViewLayoutID() {
        return R.layout.fragment_add_money;
    }

    @Override
    protected void initViewsAndEvents(View view) {
        setToolBar("待还款列表");
        mToolbar.setNavigationIcon(null);
        setDatainfo();
        setRequest();
    }
    /**
     * 绑定数据
     */
    private void setDatainfo() {
        mList = new ArrayList<>();
        setHeaderAndFooter(R.id.refresh_repay, true, true, this);

        mReclist.setLayoutManager(new LinearLayoutManager(mContext));
        mAdpter = new AllRepayListAdpter(mContext, R.layout.item_repaylist, mList);

        mReclist.setAdapter(mAdpter);
        mAdpter.setOnItemClickListener(this);
    }

    private void setRequest(){
        HttpUtils.getInstance().post(GetJsonUtils.getInstance().getRequest(HttpURL.REPAY_ALLLIST, mContext,
                new String[]{"accessid", "cur_page", "page_size"},
                new String[]{SPUtils.getAccessid(mContext), page + "", count + ""}), HttpURL.QUOTA_DETAIL, CommonValue.REQUEST_CODE1, this);
    }


    @OnClick({R.id.tvCoppy})
    public void onClick(View view) {
        switch (view.getId()){
            case R.id.tvCoppy:
                copy("zhouc@jie360.com.cn",mContext);
                showToast("复制成功");
                break;
        }
    }


    public static void copy(String content, Context context) {
// 得到剪贴板管理器
        ClipboardManager cmb = (ClipboardManager) context
                .getSystemService(Context.CLIPBOARD_SERVICE);
        cmb.setText(content.trim());
    }



    @Override
    protected void onFirstUserVisible() {
    }

    @Override
    protected void onUserVisible() {

    }

    @Override
    protected void onUserInvisible() {

    }

    @Override
    protected void DetoryViewAndThing() {

    }
    /**
     * 刷新数据
     */
    @Override
    public void getNetDate() {
        setRequest();
    }

    @Override
    public void onSuccess(String content, Info info, int requestCode) {


        switch (requestCode) {

            case CommonValue.REQUEST_CODE4:
                if (!TextUtils.isEmpty(content)) {
                    Bundle applyBundle = new Bundle();
                    applyBundle.putInt("type", 1);
                    applyBundle.putSerializable("bean", JsonUtils.getInstance().jsonToObjectk(content, ApplyOneBean.class));
                    openActivity(ApplyOneActivity.class, applyBundle);
                } else {
                    showToast("系统忙，请重试");
                }

                break;
            case CommonValue.REQUEST_CODE2:

                if (!TextUtils.isEmpty(content)) {
                    bean1 = JsonUtils.getInstance().jsonToObjectk(content, HomeWalletBean.class);
                    Log.e(TAG, "onSuccess: "+ bean1.toString());
                    if (bean1 != null) {
                        Log.e(TAG, "onSuccess: "+ bean1.getAuth_status());

                        String btnText = "";
                        if(bean1.getAuth_status() == 2){
                            btnText =  "立即提现";//2 是审核通过，文案是立即提现
                        }else if(bean1.getAuth_status() == 1 ){
                            btnText = "审核中";//1是审核中
                        }else if(bean1.getAuth_status() == 3){
                            if(bean1.getLoan_times()>1){
                                btnText = "再次申请";//3并且借款次数大于1 文案是再次申请
                            }else{
                                btnText = "重新申请";//3并且借款次数小于等于1 文案是重新申请
                            }
                        }else if(bean1.getAuth_status() == 0 && bean1.getLoan_times() > 1){
                            btnText = "再次申请";//0 并且借款次数大于1

                        }else{
                            btnText = "立即申请";//其他情况
                        }

                        mApplylend.setText(""+btnText);
                    }
                } else {
                    showToast("获取数据失败，请重新登陆");
                }
                break;
            case CommonValue.REQUEST_CODE3:
                if (!TextUtils.isEmpty(content)) {
                    Bundle bundle = new Bundle();
                    Log.e(TAG, "on获取到的WithdrawalsBean Success: "+content);

                    Gson gson = new Gson();
                    WithdrawalsBean withdrawalsBean = gson.fromJson(content, WithdrawalsBean.class);
                    bundle.putSerializable("bean", withdrawalsBean);
                    Log.e(TAG, "onSuccess: "+withdrawalsBean.toString());
                    openActivity(WithdrawalsActivity.class, bundle);
                } else {
                    showToast("系统忙，请重试");
                }
                break;
            case CommonValue.REQUEST_CODE1:
                if(!TextUtils.isEmpty(content)) {

                    if(null != mRefresh){
                        mRefresh.onFinishFreshAndLoad();
                    }
                }
                try {
                    JSONObject object = new JSONObject(content);
                    JSONArray list_info = object.getJSONArray("repay_list");
                    if (list_info.length() <= 0) {
//                llEmptyList.setVisibility(View.VISIBLE);
                        llFootView.setVisibility(View.GONE);
                        if(null != mRefresh){
                            mRefresh.setVisibility(View.GONE);
                        }
                        mNorepaylist.setVisibility(View.VISIBLE);
                        mApplylend.setOnClickListener(new View.OnClickListener() {
                            @Override
                            public void onClick(View v) {
//                        Intent intent = new Intent(mContext, HomeActivity.class);
//                        intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
//                        startActivity(intent);

//                        ((HomeActivity) getActivity()).changeFragment(0);

                                /**
                                 * 2017年9月27日 需求，此处按钮跟首页申请按钮同步
                                 */
                                if (mApplylend.getText().toString().equals("立即申请") || mApplylend.getText().toString().equals("重新申请")) {
                                    HttpUtils.getInstance().post(GetJsonUtils.getInstance().getRequest(HttpURL.AUTH_MATERIAL, mContext,
                                            new String[]{"accessid"}, new String[]{SPUtils.getAccessid(mContext)}), mContext, null, CommonValue.REQUEST_CODE4, AddMoneyFragment.this);
                                    return;
                                } else if (mApplylend.getText().toString().equals("审核中")) {
                                    showToast("审核中请勿重复申请");
                                    return;
                                } else if (mApplylend.getText().toString().equals("立即提现")) {
                                    Log.i(TAG, "onClick: " + bean1.getCredit_user_usable());
                                    if (bean1.getCredit_user_usable() != 0) {
                                        getMoneyDate();
                                    } else {
                                        showToast("您暂无可提余额");
                                        return;
                                    }
                                } else if (mApplylend.getText().toString().equals("再次申请")) {
                                    openActivity(ApplyAgainActivity.class);
                                    return;
                                }


                                EventBus.getDefault().post(new ValueEvent());
                            }
                        });
                    }
                    else {
                        if (page == 1) {
                            mList.clear();
                        }
                        if (list_info.length()>0) {
                            mNorepaylist.setVisibility(View.GONE);

                            llFootView.setVisibility(View.VISIBLE);
                            //2017年9月19日15:01:56添加支付宝账号提示
                            Log.e(TAG, "onSuccess还款列表: "+list_info.toString());
                            if(null != mRefresh){
                                mRefresh.setVisibility(View.VISIBLE);
                            }
                            Log.i(TAG, "onSuccess: "+list_info.length());
                            List<AllRepaylistBean> alllist= JsonUtils.getInstance().getList(content, "repay_list", AllRepaylistBean.class);
                            mList.addAll(alllist);
                            canLoadmore = JsonUtils.getInstance().havePage(content);
                        }
                    }
                } catch (JSONException e) {
                    e.printStackTrace();
                }

                break;

        }


        //___________________________________________________________


    }

    @Override
    public void onCacheSuccess(String content, Info info, int requestCode) {

    }
    @Override
    public void onError(Info info, int requestCode) {
        showToast(info.getMsg());
    }
    @Override
    public void onItemClick(View view, RecyclerView.ViewHolder holder, int position) {
        Bundle bundle = new Bundle();
//        bundle.putSerializable("bean", JsonUtils.getInstance().jsonToObjectk(content, AllRepaylistBean.class));
        /**
         */
        bundle.putString("repay_no", mList.get(position).getRepay_no());
        bundle.putString("pay_days",mList.get(position).getPay_days());
        bundle.putString("overdue_days",mList.get(position).getOverdue_days());
        bundle.putString("repay_end_time",mList.get(position).getRepay_end_time());
        bundle.putString("repay_amount",mList.get(position).getRepay_amount());
        bundle.putString("loan_latefee",mList.get(position).getLoan_latefee());
        bundle.putString("loan_capital",mList.get(position).getLoan_capital());
        openActivity(BackMoneyOneActivity.class, bundle);
    }
    @Override
    public boolean onItemLongClick(View view, RecyclerView.ViewHolder holder, int position) {
        return false;
    }

    private void getMoneyDate() {
        HttpUtils.getInstance().post(GetJsonUtils.getInstance().getRequest(HttpURL.LOAN_USABLE, mContext,
                new String[]{"accessid"},
                new String[]{SPUtils.getAccessid(mContext)}), mContext, null, CommonValue.REQUEST_CODE3, this);
    }

}
